package com.yx.front.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yx.front.config.global.BizException;
import com.yx.front.config.global.CommonResult;
import com.yx.front.enums.IntBoolean;
import com.yx.front.enums.TimeFormat;
import com.yx.front.model.AuditRelation;
import com.yx.front.model.FriendRelation;
import com.yx.front.model.MessageRecord;
import com.yx.front.model.SysUser;
import com.yx.front.model.param.AuditRelationParam;
import com.yx.front.model.param.FriendRelationParam;
import com.yx.front.model.vo.FriendRelationVo;
import com.yx.front.service.AuditRelationService;
import com.yx.front.service.FriendRelationService;
import com.yx.front.service.MessageRecordService;
import com.yx.front.service.SysUserService;
import com.yx.front.utils.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author YangXiong
 */
@Component
@Slf4j
public class FriendRelationManager {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private FriendRelationService friendRelationService;
    @Resource
    private AuditRelationService auditRelationService;
    @Resource
    private MessageRecordService messageRecordService;
    @Resource
    private LoginUtil loginUtil;

    public Boolean add(FriendRelationParam param) {
        if (Objects.isNull(param)) {
            throw new BizException("非法操作，参数不能为空");
        }
        SysUser currentUser = loginUtil.getCurrentUser();
        //校验是否重复添加
        LambdaQueryWrapper<AuditRelation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AuditRelation::getApplyId, currentUser.getId());
        lambdaQueryWrapper.eq(AuditRelation::getStatus, IntBoolean.NO.getKey());
        AuditRelation one2 = auditRelationService.getOne(lambdaQueryWrapper);
        if (Objects.nonNull(one2)){
            throw new BizException("已经申请过了，不要重复申请");
        }
        //校验两人是否已经是好友了
        LambdaQueryWrapper<FriendRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FriendRelation::getFriendId, param.getFriendId());
        queryWrapper.eq(FriendRelation::getUserId, currentUser.getId());
        FriendRelation one = friendRelationService.getOne(queryWrapper);
        LambdaQueryWrapper<FriendRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FriendRelation::getUserId, param.getFriendId());
        wrapper.eq(FriendRelation::getFriendId, currentUser.getId());
        FriendRelation one1 = friendRelationService.getOne(queryWrapper);
        if (Objects.isNull(one1) && Objects.isNull(one)) {
            //插入一条审核记录，去通知另外一个人
            AuditRelation auditRelation = new AuditRelation();
            auditRelation.setAuditBy(param.getFriendId());
            auditRelation.setApplyId(currentUser.getId());
            auditRelation.setCreateTime(DateUtil.date());
            auditRelation.setContext(param.getContext());
            auditRelation.setStatus(0);
            return auditRelationService.save(auditRelation);
        }
        throw new BizException("你们已经是好友了，请不要重复添加");
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean agreeApply(AuditRelationParam param) {
        //校验参数
        if (Objects.isNull(param)) {
            throw new BizException("非法操作，参数不能为空");
        }
        Long id = param.getId();
        if (Objects.isNull(id)) {
            throw new BizException("参数不能为空");
        }
        AuditRelation relation = auditRelationService.getById(id);
        if (Objects.isNull(relation)) {
            throw new BizException("非法操作，数据不存在");
        }
        UpdateWrapper<AuditRelation> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id)
                .set("status", IntBoolean.YES.getKey());
        boolean update = auditRelationService.update(updateWrapper);
        MessageRecord messageRecord = getMessageRecord(relation);
        boolean save = messageRecordService.save(messageRecord);
        if (!(save && update)) {
            throw new BizException("系统繁忙，请稍后重试");
        }
        return true;
    }

    private MessageRecord getMessageRecord(AuditRelation relation) {
        MessageRecord messageRecord = new MessageRecord();
        messageRecord.setFlag(0);
        SysUser currentUser = loginUtil.getCurrentUser();
        messageRecord.setFromId(currentUser.getId());
        messageRecord.setContext("你和" + currentUser.getUserName() + "已经是好友啦！");
        messageRecord.setSendTime(DateUtil.date());
        messageRecord.setToId(relation.getApplyId());
        return messageRecord;
    }

    public CommonResult<List<FriendRelationVo>> getFriends() {
        SysUser currentUser = loginUtil.getCurrentUser();
        LambdaQueryWrapper<FriendRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(o -> o.eq(FriendRelation::getFriendId, currentUser.getId())
                .or().eq(FriendRelation::getUserId, currentUser.getId()));
        List<FriendRelation> list = friendRelationService.list(queryWrapper);
        log.info("{}", list);
        List<FriendRelation> collect = list.stream().distinct().collect(Collectors.toList());
        log.info("列表={}", collect);
        if (CollectionUtil.isEmpty(collect)){
            return CommonResult.success(Collections.emptyList());
        }
        List<FriendRelationVo> result = handlerFriendResult(collect, currentUser.getId());
        return CommonResult.success(result);
    }

    private List<FriendRelationVo> handlerFriendResult(List<FriendRelation> collect, Long id) {
        //拿出id放到set集合，然后二次查询
        List<FriendRelationVo> vos = new ArrayList<>();
        Set<Long> ids = new HashSet<>();
        collect.forEach(one -> {
            ids.add(one.getFriendId());
            ids.add(one.getUserId());
        });
        if (CollectionUtil.isNotEmpty(ids)) {
            ids.remove(id);
        } else {
            ids.add(id);
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CollectionUtil.isNotEmpty(ids), SysUser::getId, ids);
        List<SysUser> list = sysUserService.list(wrapper);
        list.forEach(user -> {
            FriendRelationVo vo = new FriendRelationVo();
            //查询最后一条消息
            LambdaQueryWrapper<MessageRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MessageRecord::getToId, user.getId())
                    .orderByDesc(MessageRecord::getSendTime)
                    .last("limit 1");
            MessageRecord record = messageRecordService.getOne(queryWrapper);
            if (Objects.isNull(record)){
                return;
            }
            vo.setId(record.getId());
            vo.setFriendId(user.getId());
            vo.setAvatar(user.getAvatar());
            vo.setUserName(user.getUserName());
            vo.setLastMessage(record.getContext());
            vo.setSendTime(DateUtil.format(record.getSendTime(), TimeFormat.TIME_FORMAT));
            vos.add(vo);
        });
        return vos;
    }
}
